﻿using Inaction.Linq.Clause;
using Inaction.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Inaction.Linq
{
    class LinqRoot
    {
        #region 属性
        public EntitySqlStatement Statement { get; private set; }
        public List<LinqRoot> SubLinq { get; private set; }

        public LinqRoot Root { get; private set; }
        int level = 0;
        public int Level { get { return level; } }
        public string TableName { get; private set; }

        public string FormatTableName
        {
            get
            {
                return Inaction.DbProvider.Instance.FormatName(TableName);
            }
        }
        #endregion

        #region 构造
        public LinqRoot(LambdaExpression e)
        {
            Paras = new List<Mapping.ParaValue>();
            RootType = e.Parameters[0].Type;
            TableName = ClassInfo.LoadInfo(RootType).Table.Name;
            SubLinq = new List<LinqRoot>();
        }
        public LinqRoot(Type type)
        {
            Paras = new List<ParaValue>();
            RootType = type;
            TableName = ClassInfo.LoadInfo(RootType).Table.Name;
            SubLinq = new List<LinqRoot>();
        }
        public LinqRoot(LambdaExpression e, LinqRoot root)
            : this(e)
        {
            Root = root;
            level = root.Level + 1;
            TableName = "T" + level + root.SubLinq.Count;
            root.SubLinq.Add(this);
        }
        #endregion

        public Type RootType { get; private set; }
        public string WhereSql { get; private set; }
        public List<Mapping.ParaValue> Paras
        {
            get;
            private set;
        }
        public ParaValue AddPara(object value)
        {
            string name = Inaction.DbProvider.Instance.ParaFix + "P" + level;
            if (Root != null)
            {
                name += Root.SubLinq.Count;
            }
            name += Paras.Count;
            var paraValue = new Mapping.ParaValue { Name = name, Value = value};
            Paras.Add(paraValue);
            if (Root != null)
            {
                Root.Paras.Add(paraValue);
            }
            return paraValue;
        }
    }
}
